//
//  NSObject+math.m
//  helper
//
//  Created by huangyi on 12-10-29.
//  Copyright (c) 2012年 huangyi. All rights reserved.
//

#import "NSObject+math.h"

@implementation NSObject (math)

@end

float geo_distance(CGPoint gpsloc1,CGPoint gpsloc2){
    float earth=6378.137*1000;

    float p1lat=gpsloc1.y;
    float p1lng=gpsloc1.x;
    float p2lat=gpsloc2.y;
    float p2lng=gpsloc2.x;
    
    float lat1=D2R(p1lat);
    float lat2=D2R(p2lat);
    float lat=lat1-lat2;
    float lng=D2R(p1lng)-D2R(p2lng);
    float s=2*asin(sqrt(pow(sin(lat/2),2)+cos(lat1)*cos(lat2)*pow(sin(lng/2),2)));
    float length=s*earth;
    return length;
}

BOOL col_sphere(CGPoint point,CGPoint circle,CGFloat radius){
    if (radius<1) {
        radius=1;
    }
    CGFloat length2=(circle.x-point.x)*(circle.x-point.x)+(circle.y-point.y)*(circle.y-point.y);
    return radius*radius-length2>0?NO:YES;
}

BOOL col_box(CGPoint point,CGRect rect){
    BOOL l=CGRectGetMinX(rect)>point.x;
    BOOL r=CGRectGetMaxX(rect)<point.x;
    BOOL t=CGRectGetMinY(rect)>point.y;
    BOOL b=CGRectGetMaxY(rect)<point.y;
    return (l+r+t+b)?NO:YES;
}

BOOL col_hull(CGPoint point,CGPoint polygon[],int count){
    float absdegree=FLT_MAX;
    float mindegree=FLT_MAX;
    float maxdegree=FLT_MIN;
    for (int i=0; i<count; i++) {
        CGPoint point=polygon[i];
        float pointdegree=R2D(atan2f((point.x-point.x),(point.y-point.y)));
        mindegree=MIN(mindegree, pointdegree);
        maxdegree=MAX(maxdegree, pointdegree);
        absdegree=MIN(absdegree, ABS(pointdegree));
    }
    return ((maxdegree-mindegree)>180 && absdegree<90)?YES:NO;
}

static const NSString *_base58EncodingTable=@"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
extern int str2int(NSString* string){
    if (string==nil) {
        return -1;
    }
    int len=string.length;
    if (len>5) {
        return -1;
    }
    int count=_base58EncodingTable.length;
    int decode=0;
    int multi=1;
    for (int i=len-1; i>=0; i--) {
        NSString *c=[string substringWithRange:NSMakeRange(i, 1)];
        NSRange pos=[_base58EncodingTable rangeOfString:c];
        decode += multi*pos.location;
        multi=multi*count;
    }
    return decode;
}
extern NSString* int2str(int num){
    if (num<0) {
        return nil;
    }
    int count=_base58EncodingTable.length;
    NSString *str=[NSString string];
    do {
        int mod=num%count;
        num=floor(num/count);
        str=[NSString stringWithFormat:@"%@%@",[_base58EncodingTable substringWithRange:NSMakeRange(mod, 1)],str];
    } while (num);
    return str;
}
